package com.xxgame.wxtest.wxapi;

import org.cocos2dx.javascript.WeChatModule;
import org.json.JSONException;
import org.json.JSONObject;

import com.tencent.mm.opensdk.constants.ConstantsAPI;
import com.tencent.mm.opensdk.modelbase.BaseReq;
import com.tencent.mm.opensdk.modelbase.BaseResp;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;

public class WXPayEntryActivity extends Activity implements IWXAPIEventHandler{
	
	private static final String TAG = "WXPayEntryActivity";
    private IWXAPI api;
    public static String ReqWXPay = "ReqWXPay";
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Intent intent = getIntent();
    	api = WXAPIFactory.createWXAPI(this, WeChatModule.appId);
        api.handleIntent(intent, this);
        
		if (intent.hasExtra(ReqWXPay)) 
		{
			String content = intent.getStringExtra("PayContent");
			try {
				reqWXPay(content);
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		finish();
    }

	@Override
	protected void onNewIntent(Intent intent) {
		super.onNewIntent(intent);
		setIntent(intent);
        api.handleIntent(intent, this);
	}

	public void reqWXPay(String content) throws JSONException {
		JSONObject json = new JSONObject(content); 
		PayReq req = new PayReq();
		req.appId			= json.getString("appid");
		req.partnerId		= json.getString("partnerid");
		req.prepayId		= json.getString("prepayid");
		req.nonceStr		= json.getString("noncestr");
		req.timeStamp		= json.getString("timestamp");
		req.packageValue	= json.getString("package");
		req.sign			= json.getString("sign");
		req.extData			= "app data";
		api.sendReq(req);
	}
	
	@Override
	public void onReq(BaseReq req) {
		
	}

	@Override
	public void onResp(BaseResp resp) {
		Log.d(TAG, "onPayFinish, errCode = " + resp.errCode);

		if (resp.getType() == ConstantsAPI.COMMAND_PAY_BY_WX) {
			switch (resp.errCode) {
			case BaseResp.ErrCode.ERR_OK:
				WeChatModule.wxPayResultCallBack(true, "支付成功");
				break;
			case BaseResp.ErrCode.ERR_USER_CANCEL:
				WeChatModule.wxPayResultCallBack(false, "支付取消");
				break;
			case BaseResp.ErrCode.ERR_AUTH_DENIED:
				WeChatModule.wxPayResultCallBack(false, "微信验证失败");
				break;
			default:
				WeChatModule.wxPayResultCallBack(false, "支付失败");
				break;
			}	
		}
	}
}